<template>
  <div class="compet-main">
	<div style="display: inline-block;font-size:18px;margin-bottom: 15px;">
	  	<a href="#" @click="prev" style="text-decoration:none;font-size: 14px;">
	  		<icon-svg name="jiantou" style="width: 1.2em;height: 1.2em;position: relative;top: 0.3em;"></icon-svg>
	  		返回
	  	</a>
	  	<span style="display: inline-block;margin: 0 15px;color: #D9D9D9;">|</span>
	  	<span>赛事修改</span>
	</div>
	<div class="compet-content">
		<el-row>
			<el-col :span="24" >
				<span>游戏分类：</span>
				<el-select v-model="gameTypeId" class="margin15" placeholder="请选择游戏分类" style="width:200px;" @change="gameType">
					<el-option v-for="(item,index) in gameTypeIds" :key="item.index" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-col>
		</el-row>
		<el-row>
			<el-col :span="24" >
				<span>赛事分类：</span>
				<el-select v-model="eventTypeId" class="margin15" placeholder="请选择赛事分类" style="width:200px;">
					<el-option v-for="(item,index) in eventTypeIds" :key="item.index" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-col>
		</el-row>
		<el-row>
			<el-col :span="24" >
				<span>门票分类：</span>
				<el-select v-model="ticketType" class="margin15" placeholder="请选择赛事分类" style="width:200px;" @change="ticketsType">
					<el-option v-for="(item,index) in ticketTypes" :key="item.index" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-col>
		</el-row>
		<el-row>
			<el-col :span="24" >
				<span>门票价格：</span>
				<el-input style="width: 200px;" @input="changeInput" readonly class="margin15" placeholder="请输入报名费" v-model="entryMoney" autosize></el-input>
			</el-col>
		</el-row>
		<el-row>
			<el-col :span="24" >
				<span>赛事标题：</span>
				<el-input style="width: 200px;" class="margin15" placeholder="请输入标题" v-model="title" autosize></el-input>
				</el-col>
		</el-row>
		<div style="display: flex;align-items: center;margin: 2% 0;">
			<span style="display: inline-block;text-align: right;">封面图：</span>
			<div style=" width:148px;height:148px;background-color: #fbfdff; border: 1px dashed #c0ccda;border-radius: 6px;text-align: center;line-height: 148px;">
				<el-upload
					class="avatar-uploader"
					v-model="coverImg"
					action="https://admin.koudaidj.com/game/alioss/upload"
					:show-file-list="false"
					:on-success="handleAvatarSuccess"
					>
					<img v-if="coverImg" :src="coverImg" class="avatar" style="width: 148px;height: 148px;"/>
					<i v-else class="el-icon-plus avatar-uploader-icon" style="font-size: 28px;color: #8c939d"></i>
				</el-upload>
			</div>
		</div>
		<el-row>
			<el-col :span="8" >
				<span>标签：</span>
				<el-input style="width: 200px;" class="margin15" placeholder="请输入标签" v-model="tag" autosize></el-input>
			</el-col>
			<el-col :span="8" >
				<span>区域：</span>
				<el-select v-model="area" class="margin15" placeholder="请选择区域" style="width:200px;">
					<el-option v-for="(item,index) in areas" :key="item.index" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-col>
		</el-row>
		<el-row>
			<el-col :span="8" >
				<span>报名时间：</span>
				<el-date-picker
				  style="width:200px;margin-top: 15px;"
				   v-model="entryTime"
				   align="right"
				   type="datetime"
				   format="yyyy-MM-dd HH:mm:ss"
				   value-format="yyyy-MM-dd HH:mm:ss"
				   placeholder="选择报名时间"
				   >
				 </el-date-picker>
			</el-col>
		</el-row>
		<el-row>
			<el-col :span="24" >
				<span>比赛开始时间：</span>
				<el-date-picker
				  style="width:200px;margin-top: 15px;"
				   v-model="startTime"
				   align="right"
				   type="datetime"
				   format="yyyy-MM-dd HH:mm:ss"
				   value-format="yyyy-MM-dd HH:mm:ss"
				   placeholder="选择比赛开始时间"
				   >
				 </el-date-picker>
			</el-col>
		</el-row>
		<el-row>
			<el-col :span="12" >
				<span>预计人数：</span>
				<el-input style="width: 200px;" class="margin15" placeholder="请输入预计人数" v-model="needNumber" autosize></el-input>
			</el-col>
			<!-- <el-col :span="12" >
				<span>报名人数：</span>
				<el-input style="width: 200px;" class="margin15" placeholder="请输入报名人数" v-model="applyNumber" autosize></el-input>
			</el-col> -->
		</el-row>
		<el-row>
			<el-col :span="24" style="margin-top:20px;">
				<span>开启报名：</span>
				<el-radio-group v-model="status">
					<el-radio :label="1">开启</el-radio>
					<el-radio :label="2">关闭</el-radio>
				</el-radio-group>
			</el-col>
		</el-row>
		<div>
			<el-row>
				<el-col :span="8">
					<span>生成奖项：</span>
					<el-button
					class="margin15"
					  size="mini"
					  type="primary"
					   @click="awardselect">生成奖项
					</el-button>
				</el-col>
			</el-row>
			<el-row v-if="gameAwardList.length>0" v-for="(item,index) in gameAwardList" :key="index">
				<el-col :span="8">
					<span>奖项：</span>
					<el-input style="width: 200px;" class="margin15" placeholder="请输入奖项" v-model="item.title" autosize></el-input>
				</el-col>
				<el-col :span="8">
					<span>奖品：</span>
					<el-input style="width: 200px;" class="margin15" placeholder="请输入奖品" v-model="item.content" autosize></el-input>
				</el-col>
				<el-col :span="8" >
					<el-button
					v-if="index==0"
					class="margin15"
					  size="mini"
					  type="primary"
					   @click="addawards">添加
					</el-button>
					<el-button
					v-else
					class="margin15"
					  size="mini"
					  type="danger"
					   @click="deleteawards(index)">删除
					</el-button>
				</el-col>
			</el-row>
		</div>
		<div class="tinymce-content" style="display: flex;margin-top: 20px;">
		   <div style="width:134px;text-align: right;">比赛规则：</div>
		  <textarea id="tinymceId" :value="descrition" class="tinymce-textarea"/>
		</div>
		<div style="text-align: center;margin-top:30px;">
			<el-button style='margin:0 20px 0 0;' size="mini" type="primary" icon="document" @click="prev">返回上一页
			</el-button>
			<el-button size="mini" type="primary" icon="document" @click="artiReleass">保存
			</el-button>
		</div>
		<!-- 奖励类型 -->
		<el-dialog title="奖励类型" :visible.sync="dialogFormVisible" center>
			<div style="margin-bottom: 10px;">
				<span style="width: 200px;display: inline-block;text-align: right;">奖励类型：</span>
				<el-radio-group v-model="type">
				    <el-radio :label="1">击杀奖励</el-radio>
				    <el-radio :label="2">排名奖励</el-radio>
				</el-radio-group>
			</div>
			<div slot="footer" class="dialog-footer">
			  <el-button @click="dialogFormVisible = false">取 消</el-button>
			  <el-button type="primary" @click="gameNoticeTo()">确 定</el-button>
			</div>
		</el-dialog>
	</div>
  </div>
</template>

<script>
    import load from './tinymce-components/dynamicLoadScript'
    import toolbar from './tinymce-components/toolbar'
    import plugins from './tinymce-components/plugins'

    const tinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js'

    export default {
        name: 'Tinymce',
        data() {
            return{
				ticketValue: '',
				title:'',
				coverImg:'',
				tag:'',
				entryMoney:'',
				status:1,
				gameAward:{
					title:'',
					content:'',
				},
				awards:{},
				id:'',
				ticketTitle:'',
				needNumber:'',
				applyNumber:'',
				gameAwardList:[],
				startTime:'',
				detail:'',
				prepareTime:'',
				entryTime:'',
				eventStatus:'',
				createTime:'',
                tinymceId: 'tinymceId',
                height: 435,
                toolbar: [],
				gameName:'',
				type:1,
				ticketType:'',
				ticketTypes:[],
				eventTypeId:'',
				eventTypeIds:[],
				dialogFormVisible:false,
                menubar: 'file edit insert view format table',
                languageTypeList: {
                    'en': 'en',
                    'zh': 'zh_CN'
                },
				artiCletypes: [],
                // 富文本内容
                descrition: '',
				gameTypeId:'',
				gameTypeIds:[],
				area:'',
				areas:[
					{
						value:1,
						label:'微信区'
					},
					{
						value:2,
						label:'QQ区'
					}
				],
            }
        },
        watch: {
            descrition(val) {
                if (!this.hasChange && this.hasInit) {
                    this.$nextTick(() => window.tinymce.get(this.tinymceId).setContent(val || ''))
                }
            }
        },
        methods: {
			changeInput() {
			      var pattern = /^[0-9][0-9]*$/ // 正整数的正则表达式
			      // 不符合正整数时
			      if (!pattern.test(this.entryMoney)) {
			        // input 框绑定的内容为空
			        this.entryMoney = ''
			      }
			},
			handleAvatarSuccess(file,fileList) {
				this.coverImg = file.data
			},
			handleChange(file, fileList){
				this.hideUpload = fileList.length >= this.limit;
			},
			handleRemove(file, fileList) {
				this.hideUpload = fileList.length >= this.limit;
			},
			// 返回上一级
			prev(){
				this.$router.back()
			},
			// 生成奖项
			awardselect(){
				if (this.gameTypeId == '') {
				    this.$notify({
				        title: '提示',
				        duration: 1800,
				        message: '请选择游戏分类',
				        type: 'warning'
				    });
				    return
				}
				if (this.entryMoney == '' && this.tickeType != '13') {
				    this.$notify({
				        title: '提示',
				        duration: 1800,
				        message: '请输入报名费',
				        type: 'warning'
				    });
				    return
				}
				if (this.gameName == '和平精英') {
				    this.dialogFormVisible = true
				}else{
					this.$http({
					  url: this.$http.adornUrl2('/gameAward/createAward'),
					  method: 'get',
					  params: this.$http.adornParams({
						  'gameTypeId':this.gameTypeId,
						  'money':this.entryMoney,
						  'type':this.type
					  })
					}).then(({data}) => {
					  this.tableDataLoading = false
					  let returnData = data.data
					  this.awards = returnData
					  this.gameAwardList = this.awards
					})  
				}
			},
			gameNoticeTo(){
				this.$http({
				  url: this.$http.adornUrl2('/gameAward/createAward'),
				  method: 'get',
				  params: this.$http.adornParams({
					  'gameTypeId':this.gameTypeId,
					  'money':this.entryMoney,
					  'type':this.type
				  })
				}).then(({data}) => {
				  let returnData = data.data
				  this.awards = returnData
				  this.gameAwardList = this.awards
				  this.dialogFormVisible = false
				}) 
			},
			// 获取游戏名称
			gameType(val){
				 let obj = {};
				  obj = this.gameTypeIds.find((item)=>{//这里的userList就是上面遍历的数据源
					  return item.value === val;//筛选出匹配数据
				  });
				this.gameName = obj.label
			},
			// 报名费
			ticketsType(val){
				let obj = {};
				     obj = this.ticketTypes.find((item)=>{//这里的userList就是上面遍历的数据源
				         return item.value === val;//筛选出匹配数据
				     });
				this.entryMoney = obj.money
				this.ticketTitle = obj.label
				this.ticketValue = obj.value
			},
			// 添加奖项
			addawards(){
				let awardsnum = {
					content:'',
					title:''
				}
				this.gameAwardList.push(awardsnum)
			},
			// 删除奖项
			deleteawards(index){
				this.gameAwardList.splice(index, 1);
			},
			init() {
			        load(tinymceCDN, (err) => {
			            if (err) {
			                this.$message.error(err.message)
			                return
			            }
			            this.initTinymce()
			        })
			      let id = this.$route.query.id
			      this.$http({
			        url: this.$http.adornUrl2('/gameEvent/find'),
			        method: 'get',
			        params: this.$http.adornParams({
			          'id':id
			        })
			      }).then(({data}) => {
			        let returnData = data.data;
					this.id = returnData.id
			        this.area = returnData.area
			        this.coverImg = returnData.coverImg
			        this.entryMoney = returnData.entryMoney;
			        this.entryTime =returnData.entryTime,
			        this.tag = returnData.tag;
			        this.title = returnData.title;
			        this.status = returnData.status;
			        this.price = returnData.price;
			        this.sales = returnData.sales;
					this.eventStatus =returnData.eventStatus
			        this.startTime = returnData.startTime;
			        this.status = returnData.status;
			        this.prepareTime = returnData.prepareTime;
			        this.gameTypeId = returnData.gameTypeId;
			        this.descrition = returnData.detail;
					this.createTime = returnData.createTime;
					this.needNumber = returnData.needNumber;
					this.applyNumber = returnData.applyNumber;
					this.eventTypeId = returnData.eventTypeId;
			        this.gameAwardList = returnData.gameAwardList;
					this.awards.title = this.gameAwardList[0].title
					this.awards.content = this.gameAwardList[0].content
					this.ticketType = returnData.ticketType
					this.ticketTitle = returnData.ticketTitle
					let obj = {};
					obj = this.gameTypeIds.find((item)=>{//这里的userList就是上面遍历的数据源
						  return item.value === this.gameTypeId;//筛选出匹配数据
					});
					this.gameName = obj.label
			      })
			    },
				// 修改赛事
				artiReleass(){
					if (this.gameTypeId == '') {
					    this.$notify({
					        title: '提示',
					        duration: 1800,
					        message: '请选择游戏分类',
					        type: 'warning'
					    });
					    return
					}
					if (this.title == '') {
					    this.$notify({
					        title: '提示',
					        duration: 1800,
					        message: '请输入赛事标题',
					        type: 'warning'
					    });
					    return
					}
					if (this.coverImg == '') {
					    this.$notify({
					        title: '提示',
					        duration: 1800,
					        message: '请上传封面图',
					        type: 'warning'
					    });
					    return
					}
					if (this.tag == '') {
					    this.$notify({
					        title: '提示',
					        duration: 1800,
					        message: '请输入标签',
					        type: 'warning'
					    });
					    return
					}
					if (this.area == '') {
					    this.$notify({
					        title: '提示',
					        duration: 1800,
					        message: '请选择区域',
					        type: 'warning'
					    });
					    return
					}
					if (this.entryMoney == '' && this.ticketType != '13') {
					    this.$notify({
					        title: '提示',
					        duration: 1800,
					        message: '请输入报名费',
					        type: 'warning'
					    });
					    return
					}
					if (this.entryTime == '') {
					    this.$notify({
					        title: '提示',
					        duration: 1800,
					        message: '请选择报名时间',
					        type: 'warning'
					    });
					    return
					}
					if (this.needNumber == '') {
					    this.$notify({
					        title: '提示',
					        duration: 1800,
					        message: '请输入预计报名人数',
					        type: 'warning'
					    });
					    return
					}
					if (this.startTime == '') {
					    this.$notify({
					        title: '提示',
					        duration: 1800,
					        message: '请选择比赛开始时间',
					        type: 'warning'
					    });
					    return
					}
					if (Date.parse(this.startTime) <= Date.parse(this.entryTime)) {
					    this.$notify({
					        title: '提示',
					        duration: 1800,
					        message: '比赛开始时间不能小于等于报名时间',
					        type: 'warning'
					    });
					    return
					}
					if (this.gameAwardList == '') {
					    this.$notify({
					        title: '提示',
					        duration: 1800,
					        message: '请生成奖项',
					        type: 'warning'
					    });
					    return
					}
					if (this.descrition == '') {
					    this.$notify({
					        title: '提示',
					        duration: 1800,
					        message: '请输入比赛规则',
					        type: 'warning'
					    });
					    return
					}
					this.$http({
					  url: this.$http.adornUrl2('/gameEvent/update'),
					  method: 'post',
					  data: this.$http.adornData({
						'id':this.id,
						'area':this.area,
						'coverImg':this.coverImg,
						'entryMoney':this.entryMoney,
						'entryTime':this.entryTime,
						'tag':this.tag,
						'title':this.title,
						'status':this.status,
						'startTime':this.startTime,
						'prepareTime':this.prepareTime,
						'needNumber':this.needNumber,
						'applyNumber':this.applyNumber,
						'gameTypeId':this.gameTypeId,
						'detail':this.descrition,
						'createTime':this.createTime,
						'eventStatus':this.eventStatus,
						'gameAwardList':this.gameAwardList,
						'eventTypeId':this.eventTypeId,
						'ticketType':this.ticketType,
						'ticketTitle':this.ticketTitle
					  })
					}).then(({data}) => {
						this.$message({
						  message: '操作成功',
						  type: 'success',
						  duration: 1500,
						  onClose: () => {
							this.$router.push({path: '/competition'})
						  }
					})
				})
			},
            initTinymce() {
                const _this = this
                window.tinymce.init({
                    selector: `#${this.tinymceId}`,
                    images_upload_handler: function (blobInfo, success, failure) {
                        var xhr, formData;

                        xhr = new XMLHttpRequest();
                        xhr.withCredentials = false;
                        xhr.open('POST', "https://admin.koudaidj.com/game/alioss/upload");
                        xhr.onload = function () {
                            var json;

                            if (xhr.status != 200) {
                                failure('HTTP Error: ' + xhr.status);
                                return;
                            }
                            json =JSON.parse(xhr.responseText);
                            if (json == "" || json == null) {
                                failure('Invalid JSON: ' + xhr.responseText);
                                return;
                            }
                            success(json.data);
                        };
                        formData = new FormData();
                        formData.append('file', blobInfo.blob(), blobInfo.filename());
                        xhr.send(formData);
                    },
                    language: this.languageTypeList['zh'],
                    height: this.height,
                    body_class: 'panel-body ',
                    object_resizing: false,
                    toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
                    plugins,
                    menubar: this.menubar,
                    end_container_on_empty_block: true,
                    powerpaste_word_import: 'clean',
                    code_dialog_height: 450,
                    code_dialog_width: 1000,
                    advlist_bullet_styles: 'square',
                    advlist_number_styles: 'default',
                    imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
                    default_link_target: '_blank',
                    link_title: false,
                    // Image
                    imagetools_toolbar: 'rotateleft rotateright | flipv fliph | editimage imageoptions',
                    nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
                    init_instance_callback: editor => {
                        if (_this.descrition) {
                            editor.setContent(_this.descrition)
                        }
                        _this.hasInit = true
                        editor.on('NodeChange Change KeyUp SetContent', () => {
                            this.hasChange = true
                            this.descrition = editor.getContent()
                        })
                    },
                    setup(editor) {
                        editor.on('FullscreenStateChanged', (e) => {
                            _this.fullscreen = e.state
                        })
                    }
                })
            },
            destroyTinymce() {
                const tinymce = window.tinymce.get(this.tinymceId)
                if (this.fullscreen) {
                    tinymce.execCommand('mceFullScreen')
                }
                if (tinymce) {
                    tinymce.destroy()
                }
            },
			
			  // 删除商品属性
			  deleter(index){
				let length = this.sku.length
				if(length == 1){
				  this.$message({
					  title: '提示',
					type: 'error',
					  duration: 1800,
					  message: '属性至少要有一个',
					  type: 'warning'
				  });
				  return
				}else{
				  this.sku.splice(index, 1);
				}
			},
			deleterule(index){
				this.ruleValue.splice(index, 1);
			},
			// 获取游戏分类
			gameClass(){
				this.$http({
				  url: this.$http.adornUrl2('/gameType/result'),
				  method: 'get',
				  params: this.$http.adornParams({
				  })
				}).then(({data}) => {
				  this.tableDataLoading = false
				  let returnData = data.data
				  this.gameTypeIds = returnData
				})  
			},
			// 获取赛事分类
			competClass(){
				this.$http({
				  url: this.$http.adornUrl2('/gameEventType/result'),
				  method: 'get',
				  params: this.$http.adornParams({
				  })
				}).then(({data}) => {
				  this.tableDataLoading = false
				  let returnData = data.data
				  this.eventTypeIds = returnData
				})  
			},
			// 门票分类
			ticketClass(){
				this.$http({
				  url: this.$http.adornUrl2('/goods/ticketResult'),
				  method: 'get',
				  params: this.$http.adornParams({
				  })
				}).then(({data}) => {
				  let returnData = data.data
				  this.ticketTypes = returnData
				})  
			}
        },
        mounted() {
            this.init()
			this.gameClass()
			this.competClass()
			this.ticketClass()
        },
        beforeDestroy() {
            this.destroyTinymce()
        },
        activated() {
            if (window.tinymce) {
                this.initTinymce()
            }
        },
        deactivated() {
            this.destroyTinymce()
        }
    }
</script>

<style scoped="scoped">
	.compet-content span{
		display: inline-block;
		width:120px;
		text-align: right;
	}
	
	
  .main-cont {
    max-width: 100%;
    min-width: 80%;
	padding-bottom:5%;
	background-color: #fff;
  }

  .tinymce-container {
    position: relative;
    line-height: normal;
  }

  .tinymce-container >>> .mce-fullscreen {
    z-index: 10000;
  }

  .tinymce-textarea {
    visibility: hidden;
    z-index: -1;
  }
 .hide .el-upload--picture-card {
     display: none;
 }
 .margin15{margin-right: 15px;margin-top: 15px;}
 .ruleitem {padding-left:10px;margin-top: 15px;}
 .ruleitem .ruleicon{position: relative;top: 3px; left:2px;width:1.2em;height:1.2em;}
 .el-tag + .el-tag {
     margin-left: 10px;
   }
   .button-new-tag{
     height: 32px;
     line-height: 31px;
     padding-top: 0;
     padding-bottom: 0;
 	border-radius: 4px;
 	border-top-left-radius: 0;
 	border-bottom-left-radius: 0;
 	background-color: #f5f7fa;
 	position: relative;
 	left: -5px;
 	border-color: #dcdfe6;
 	border: 1px solid #dcdfe6;
   }
   .input-new-tag {
     width: 90px;
     margin-left: 10px;
     vertical-align: bottom;
   }
   .el-input--small .el-input__inner{
 	  border-top-right-radius: 0;
 	  border-bottom-right-radius: 0;
    }
	.el-table--enable-row-transition .el-table__body td{
		text-align: center;
	}
	.imgWrap .avatar-uploader .el-upload{
		width: 60px;
	}
	.el-table .cell{
		text-align: center!important;
	}
	.el-tag--medium{margin-right: 10px;}
</style>
